package com.pioneer.swing.controller;

import com.pioneer.beans.*;
import com.pioneer.swing.ui.UIConstants;
import com.pioneer.swing.PioneerApp;
import com.pioneer.dao.*;
import com.pioneer.util.AppProperties;

import javax.swing.JComboBox;
import javax.swing.DefaultCellEditor;
import java.text.NumberFormat;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.IOException;
import java.text.DecimalFormat;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.util.Vector;
import java.util.Properties;

import org.jdom.transform.JDOMSource;
import org.jdom.transform.JDOMResult;
import org.jdom.Document;
import org.jdom.output.XMLOutputter;
import javax.xml.transform.stream.StreamSource;
import org.apache.fop.apps.Driver;
import org.apache.fop.layout.Page;
import org.apache.fop.apps.FOPException;
import org.xml.sax.XMLReader;

import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;

import java.awt.print.PrinterJob;
import java.awt.print.PrinterException;
import org.apache.fop.render.awt.AWTRenderer;





/**
 * Title:        Pioneer Metals
 * Description:
 * Copyright:    Copyright (c) 2001
 * Company:      Pioneer Metals
 * @author Gary Chen
 * @version 1.0
 */

public class Printer
extends AWTRenderer
implements ActionListener {
	
	private final String XSL_FILE_MANIFEST="manifest.xsl";
	private final String XSL_FILE_JOBQUOTE="job_quote.xsl";
	

  private ManifestDAO manifestDAO;
	private JobDAO jobDAO;
	private ContactDAO contactDAO;

  public Printer() {
	super(null);	
  }
	
	public void setManifestDAO(ManifestDAO manifestDAO) {
		this.manifestDAO=manifestDAO;
	}
	
	public void setContactDAO(ContactDAO contactDAO) {
		this.contactDAO = contactDAO;
	}
	
	public void setJobDAO(JobDAO jobDAO) {
		this.jobDAO = jobDAO;
	}

  public static void main(String[] args) {
  }

  public void actionPerformed(ActionEvent e) {
    String actionCommand=e.getActionCommand();
    Object queryObj=e.getSource();

    if ((actionCommand.equals(UIConstants.COMMAND_PRINT_MANIFEST)) || (actionCommand.equals(UIConstants.COMMAND_PRINT_JOB)))
    {
		System.out.println("Action command: "+actionCommand);
		Key key=((Keyed)queryObj).getKey();
		printDoc(key,actionCommand);
	}
	
  }

	
	private void printDoc(Key key, String actionCommand)
	{
		Document doc = null;
		String xslFileName = null;
		System.out.println(key.getClass().getName());
		if (key instanceof ManifestKey) {
			String jobNum=((ManifestKey)key).getJobNum();
			try {
				Manifest manifest=manifestDAO.getManifest(jobNum);
				doc=manifest.getDocRep();
				xslFileName = AppProperties.getProperty(AppProperties.MANIFEST_XSL);
			}
			catch (DataAccessException ex) {
				System.err.println("Could not retrieve manifest for printing");
			}
		}
		else if (key instanceof JobKey) {
			
			String quoteNum = ((JobKey)key).getQuoteNums()[0];
			try {
				Job job = jobDAO.getJob(quoteNum);
				doc = job.getDocRep(contactDAO,jobDAO);
				xslFileName = AppProperties.getProperty(AppProperties.JOB_QUOTE_XSL);
			}
			catch (DataAccessException ex) {
				System.err.println("Could not retrieve quote for printing");
			}
			
		}
		
		if (doc!=null) {
			XMLOutputter output=new XMLOutputter(" ",true);;
			try {
				output.output(doc,System.out);
			}
			catch ( Exception ex) {
				System.err.println("Could not marshall XML to standard out");
			}

			Document fop=null;
			try {
				Transformer transformer = TransformerFactory.newInstance().newTransformer(
					new StreamSource(new FileInputStream(AppProperties.CONFIG_PATH+File.separator+xslFileName)));
				JDOMResult out=new JDOMResult();
				transformer.transform(new JDOMSource(doc), out);
				fop=out.getDocument();
				//Properties pathProp = new Properties();
				//pathProp.load(new FileInputStream(AppProperties.CONFIG_PATH+java.io.File.separator+AppProperties.PATHPROP));							
				String userDir = AppProperties.getProperty(AppProperties.USERDIR);				
				String pdfFile = AppProperties.getProperty(AppProperties.PDF_FILE);
				String pdfCacheFile=userDir+File.separator+pdfFile;
				System.out.println("Cache file at "+pdfCacheFile);
				//String pdfCacheFile=System.currentTimeMillis()+".pdf";
				FileOutputStream fos=new FileOutputStream(pdfCacheFile);
				Driver driver = new Driver(new JDOMSource(fop).getInputSource(),fos);
				driver.setRenderer(Driver.RENDER_PDF);
				driver.run();
				fos.close();
				
				String userfileLocation = AppProperties.getProperty(AppProperties.USERFILE);
				//Properties userprops = new Properties();
				//userprops.load(new java.io.FileInputStream(userfileLocation));			
				
				String acrobatCmd = AppProperties.getProperty(AppProperties.ACROBAT_COMMAND);
				String command = acrobatCmd+" "+pdfCacheFile;
				System.out.println("Using Acrobat Reader command: "+command);				
				Runtime.getRuntime().exec(command);
				//Runtime.getRuntime().exec(pdfCacheFile);
			}
			catch (TransformerException e) {
				e.printStackTrace(System.err);
			}
			catch (IOException e) {
				e.printStackTrace(System.err);
			}
			catch (FOPException e) {
				e.printStackTrace(System.err);
			}
		}
	}
}